<template>
  <div class="app-container">
    <controlNumberDialog
      :form-dialog="formDialog"
      :control-number-obj="controlNumberObj"
      :old-control-number-obj="oldControlNumberObj"
      @confirmModify="confirmModify"
    />
    <selectFormDialog
      :form-dialog="formDialog"
      :select-form-obj="selectFormObj"
      :select-form-info="selectFormInfo"
      @selectFormModify="selectFormModify"
    />

    <formConDialog v-if="formDialogVisible" :form-dialog="formDialogVisible" />

    <!--顶部搜索框-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="文件名称">
        <el-input
          v-model="searchForm.fileName"
          style="width: 200px"
          placeholder="请输入文件名称"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          style="margin-left: 10px"
          @click="searchFileName"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
    <!--表格-->
    <el-row>
      <el-col :span="24">
        <el-table :data="recordInfo.records" stripe>
          <el-table-column type="index" label="序号" align="center" />
          <el-table-column label="表单名称" prop="fileName" align="left" />
          <el-table-column label="源表单" prop="parentName" align="center" />
          <el-table-column label="文件控制编号" prop="fileNo" align="center" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <!--:disabled="scope.row.parentName!=null?false:true"-->
              <el-button
                :disabled="scope.row.parentName != null"
                type="text"
                @click="toFormCon(scope.row)"
                >表单配置</el-button
              >
              <el-button type="text" @click="selectFactorAndStandard(scope.row)"
                >关联因子配置</el-button
              >
              <el-button type="text" @click="viewFactorAndStandard(scope.row)"
                >已关联因子</el-button
              >
              <!-- <el-button
                v-show="scope.row.parentName == null"
                type="text"
                @click="clickSelectForm(scope.row)"
                >选择源表单</el-button
              > -->
              <!-- <el-button
                v-show="scope.row.parentName != null"
                type="text"
                @click="cancelSelectForm(scope.row)"
                >取消源表单</el-button
              > -->

              <el-button type="text" @click="clickControlNumber(scope.row)"
                >控制编号编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-pagination
      :current-page="pageData.pageNumber"
      :page-sizes="pageSizeList"
      :page-size="pageData.pageSize"
      :total="recordInfo.total"
      layout="total, sizes, prev, pager, next, jumper"
      style="text-align: right;margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 查看关联因子和标准弹框 -->
    <el-dialog
      title="查看关联因子和标准"
      :visible.sync="factorDialogVisible"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-table :data="factorData" stripe style="width: 100%">
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column label="检测对象" prop="className" align="center" />
        <el-table-column label="检测因子" prop="factorName" align="center" />
        <el-table-column label="标准号" prop="standardNo" align="center" />
        <el-table-column label="检测标准" prop="standardName" align="center" />
        <el-table-column
          label="分析方法"
          prop="analysisMethod"
          align="center"
        />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="factorDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="factorVisible"
      append-to-body
      width="85%"
      :close-on-click-modal="false"
      top="5vh"
    >
      <el-radio-group v-model="radio1">
        <el-radio-button label="1">因子</el-radio-button>
        <el-radio-button label="2">因子套餐</el-radio-button>
      </el-radio-group>
      <div>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-card class="card-left" shadow="never">
              <div v-if="radio1 == 1">
                <el-tree
                  ref="tree"
                  class="filter-tree"
                  :data="factorTreeData"
                  :props="defaultProps"
                  highlight-current
                  default-expand-all
                  :expand-on-click-node="true"
                  style="height: 100%;"
                  @node-click="handleTreeFactorSearch"
                />
              </div>
              <div v-if="radio1 == 2">
                <el-card class="card-left" shadow="never">
                  <div
                    v-for="(item, index) in factorGroupData"
                    :key="index"
                    class="text dialog-item"
                    @click="choseItem(item)"
                  >
                    {{ item.groupName }}
                  </div>
                </el-card>
              </div>
            </el-card>
          </el-col>

          <!-- 因子选择部分 -->
          <el-col :span="18" v-if="radio1 == 1">
            <el-container>
              <el-header height="45px">
                <el-input
                  v-model.trim="factorForm.fuzzy"
                  style="width:320px"
                  placeholder="请输入因子/标准号/检测标准"
                  @keyup.enter.native="handleFactorSearch"
                />
                <el-button
                  type="primary"
                  style="margin-left: 10px"
                  @click="handleFactorSearch"
                  >查询</el-button
                >
              </el-header>
              <el-main class="main-body">
                <el-table
                  ref="factorTable"
                  :data="showChoseData"
                  stripe
                  border
                  max-height="450px"
                  :header-cell-style="{ background: '#ECF3FC' }"
                  @selection-change="handleFactorSelectionChange"
                  :row-key="getRowKeys"
                >
                  <el-table-column
                    type="selection"
                    width="50"
                    align="center"
                    :reserve-selection="true"
                  />
                  <el-table-column
                    prop="className"
                    label="检测对象"
                    width="100px"
                    align="center"
                  />
                  <el-table-column
                    prop="factorName"
                    label="检测因子"
                    align="center"
                  />
                  <el-table-column
                    prop="standardNo"
                    label="标准号"
                    align="center"
                  />
                  <el-table-column
                    prop="standardName"
                    label="标准名称"
                    min-width="130px"
                    align="center"
                  />
                  <el-table-column
                    prop="analysisMethod"
                    label="分析方法"
                    align="center"
                  />
                </el-table>
              </el-main>
              <el-footer height="45px" v-if="radio1 == 1">
                <pagination
                  v-show="factTotal > 0"
                  :total="factTotal"
                  :page.sync="factorForm.pageNumber"
                  :limit.sync="factorForm.pageSize"
                  @pagination="handleFactorSearch"
                />
              </el-footer>
            </el-container>
          </el-col>

          <!-- 因子套餐选择部分 -->
          <el-col :span="18" v-else>
            <el-container>
              <el-header height="45px">
                <el-input
                  v-model.trim="groupForm.fuzzy"
                  style="width:320px"
                  placeholder="请输入因子/标准号/检测标准"
                  @keyup.enter.native="handleGroupSearch"
                />
                <el-button
                  type="primary"
                  style="margin-left: 10px"
                  @click="handleGroupSearch"
                  >查询</el-button
                >
              </el-header>
              <el-main class="main-body">
                <el-table
                  ref="groupTable"
                  :data="showChoseData"
                  stripe
                  border
                  max-height="450px"
                  :header-cell-style="{ background: '#ECF3FC' }"
                  @selection-change="handleGroupSelectionChange"
                  :row-key="getRowKeys"
                >
                  <el-table-column
                    type="selection"
                    width="50"
                    align="center"
                    :reserve-selection="true"
                  />
                  <el-table-column
                    prop="className"
                    label="检测对象"
                    width="100px"
                    align="center"
                  />
                  <el-table-column
                    prop="factorName"
                    label="检测因子"
                    align="center"
                  />
                  <el-table-column
                    prop="standardNo"
                    label="标准号"
                    align="center"
                  />
                  <el-table-column
                    prop="standardName"
                    label="标准名称"
                    min-width="130px"
                    align="center"
                  />
                  <el-table-column
                    prop="analysisMethod"
                    label="分析方法"
                    align="center"
                  />
                </el-table>
              </el-main>
            </el-container>
          </el-col>
        </el-row>

        <el-divider content-position="left">已选因子</el-divider>
        <el-row style="min-height:36px;line-height: 30px">
          <el-col :span="24">
            <el-table
              :data="choseFatcors"
              stripe
              border
              style="width: 100%"
              max-height="400"
              :header-cell-style="{ background: '#ECF3FC' }"
            >
              <el-table-column
                type="index"
                label="序号"
                width="50"
                align="center"
              />
              <el-table-column
                prop="className"
                label="检测对象"
                align="center"
              />
              <el-table-column label="检测因子" align="center">
                <template slot-scope="scope">
                  <span class="ellipsis" :title="scope.row.factorName">{{
                    scope.row.factorName
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="standardNo"
                label="标准号"
                align="center"
              />
              <el-table-column
                prop="standardName"
                label="检测标准"
                align="center"
              />
              <el-table-column
                prop="analysisMethod"
                label="分析方法"
                align="center"
              />
              <el-table-column label="操作" align="center" width="80">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleClose(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="factorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmChoseFactor">确认</el-button>
      </div>
    </el-dialog>
    <!-- 名称选择弹框 -->
    <el-dialog
      title="选择表单名称"
      :visible.sync="nameSelectionDialog.visible"
      width="400px"
      :close-on-click-modal="false"
      @close="handleNameDialogClose"
    >
      <el-form>
        <el-form-item
          label="表单名称"
          prop="selectedName"
          :rules="{
            required: true,
            message: '请选择表单名称',
            trigger: 'change'
          }"
        >
          <el-select
            v-model="nameSelectionDialog.selectedName"
            placeholder="请选择表单名称"
            style="width: 100%"
          >
            <el-option
              v-for="name in nameSelectionDialog.names"
              :key="name"
              :label="name"
              :value="name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="nameSelectionDialog.visible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="confirmNameSelection"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as formConfigurationsServer from "@/api/system/formConfigurations";
import * as dictServer from "@/api/dict";
import * as factorServer from "@/api/factor";
import commonMixins from "../../../mixins/commonMixins.js";
import controlNumberDialog from "./samplingRecord/ControlNumberDialog.vue";
import selectFormDialog from "./samplingRecord/SelectFormDialog.vue";
import formConDialog from "./samplingRecord/formConDialog.vue";
export default {
  name: "SamplingRecord",
  components: { controlNumberDialog, selectFormDialog, formConDialog },
  mixins: [commonMixins],
  data() {
    return {
      // 表单配置
      formDialogVisible: false,
      // 搜索
      searchForm: {},
      // 列表数据
      recordInfo: {},
      // 点击控制编号需要传递过去的数据
      controlNumberObj: {},
      oldControlNumberObj: {},

      // 选择源表单弹框
      // 获取表单名称
      selectFormObj: {},
      // 调接口拿到的下拉框
      selectFormInfo: [],
      factorDialogVisible: false,
      factorData: [],
      factorVisible: false,
      factorTreeData: [],
      factorGroupData: [],
      defaultProps: {
        children: "children",
        label: "name",
        id: "id"
      },
      factTotal: 0,
      factorForm: {
        fuzzy: "",
        classId: "",
        factorName: "",
        pageNumber: 1,
        pageSize: 10
      },
      fileResourceId: "",
      fileResourceName: "",
      fileResourceCode:"",
      choseFatcors: [], // 已选因子列表
      selectedIds: new Set(),
      radio1: "1",
      groupForm: {
        fuzzy: "",
        groupId: ""
      },
      factorChoseData: [], // 因子选项卡的数据
      groupChoseData: [], // 因子套餐选项卡的数据
      showChoseData: [], // 当前显示的数据
      factorSelection: [], // 因子选择
      groupSelection: [], // 套餐选择
      name: "",
      selectedGroupItems: new Map(),
      nameSelectionDialog: {
        visible: false,
        names: [], // 存储可选择的名称数组
        selectedName: "" // 存储选中的名称
      }
    };
  },
  watch: {
    pageData: {
      handler() {
        this.queryRecord();
      },
      deep: true
    },
    radio1: {
      handler(newVal) {
        if (newVal === "1") {
          // 切换到因子选项卡
          this.showChoseData = [...this.factorChoseData];
          this.$nextTick(() => {
            if (this.$refs.factorTable) {
              this.$refs.factorTable.clearSelection();
              this.factorSelected.forEach(row => {
                const target = this.showChoseData.find(
                  item => item.id === row.id
                );
                if (target) {
                  this.$refs.factorTable.toggleRowSelection(target, true);
                }
              });
            }
          });
        } else {
          // 切换到套餐选项卡
          this.showChoseData = [...this.groupChoseData];
          this.$nextTick(() => {
            if (this.$refs.groupTable) {
              this.$refs.groupTable.clearSelection();
              this.groupSelected.forEach(row => {
                const target = this.showChoseData.find(
                  item => item.id === row.id
                );
                if (target) {
                  this.$refs.groupTable.toggleRowSelection(target, true);
                }
              });
            }
          });
        }
      }
    }
  },
  created() {
    this.queryRecord();
  },
  methods: {
    // 搜索
    searchFileName() {
      this.queryRecord();
    },
    // 列表的查询
    queryRecord() {
      formConfigurationsServer
        .queryRecordApi({
          fileCode: "SYS",
          ...this.searchForm,
          ...this.pageData
        })
        .then(res => {
          // console.log("query",res);
          if (res.code == 200 && res.result) {
            this.recordInfo = res.result;
          }
        });
    },
    // 点击控制编号编辑按钮函数
    clickControlNumber(row) {
      // console.log(row);
      this.formDialog.controlNumber = true;
      this.controlNumberObj = { ...row };
      this.oldControlNumberObj = { ...row };
    },
    // 点击选择源表单按钮函数
    clickSelectForm(row) {
      // console.log(row);
      this.formDialog.selectForm = true;
      this.selectFormObj = { ...row };
      formConfigurationsServer
        .querySelectFormApi({ fileCode: "XC" })
        .then(res => {
          // console.log(res.result);
          if (res.code == 200) {
            this.selectFormInfo = res.result;
            // let obj=this.selectFormInfo.find(item=>{
            //     return item.id==this.selectFormObj.parentId;
            // });
            // if (this.selectFormObj.fileName ==obj.fileName){
            //     this.selectFormObj.parentId="";
            // }
          }
        });
    },

    // 点击取消源表单按钮函数
    cancelSelectForm(obj) {
      // console.log(obj);
      formConfigurationsServer.updateSelectFormApi({ id: obj.id }).then(res => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "取消成功"
          });
          this.queryRecord();
        } else {
          this.$message({
            type: "success",
            message: "取消失败"
          });
        }
      });
    },

    // controlNumber弹框传递过来的数据
    confirmModify(obj) {
      formConfigurationsServer
        .updateControlNumberApi({ id: obj.id, fileNo: obj.fileNo })
        .then(res => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "修改成功"
            });
            this.queryRecord();
          } else {
            this.$message({
              type: "success",
              message: "修改失败"
            });
          }
        });
    },

    // 点击选择源表单修改（子组件源表单修改）
    selectFormModify(obj) {
      const selectFormObj = this.selectFormInfo.find(item => {
        return item.id == obj.parentId;
      });
      formConfigurationsServer
        .updateSelectFormApi({ id: obj.id, parentId: obj.parentId })
        .then(res => {
          // console.log(res);
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "修改成功"
            });
            this.queryRecord();
          } else {
            this.$message({
              type: "success",
              message: "修改失败"
            });
          }
        });
    },

    // 点击表单配置跳转路由
    toFormCon(row) {
      if (row.names != null) {
        if (row.names.length > 1) {
          // 如果有多个名称，显示选择弹框
          this.nameSelectionDialog.names = row.names;
          this.nameSelectionDialog.selectedName = "";
          this.nameSelectionDialog.rowData = row; // 保存行数据
          this.nameSelectionDialog.visible = true;
        } else {
          // 如果只有一个名称，直接跳转
          this.navigateToForm(row.names[0], row);
        }
      } else {
        this.$message({
          type: "warning",
          message: "默认表单不能为空！"
        });
      }
    },

    // 处理名称选择确认
    confirmNameSelection() {
      if (!this.nameSelectionDialog.selectedName) {
        this.$message({
          type: "warning",
          message: "请选择表单名称"
        });
        return;
      }

      this.navigateToForm(
        this.nameSelectionDialog.selectedName,
        this.nameSelectionDialog.rowData
      );
      this.nameSelectionDialog.visible = false;
    },

    // 实际跳转逻辑
    navigateToForm(name, row) {
      let fileName = name;

      window.open(
        "http://8.136.159.136:9528/" +
          "&token=" +
          this.$store.getters.token +
          "&id=" +
          row.id +
          "#/hzform/designer/" +
          fileName
      );
    },
    // 处理弹框关闭
    handleNameDialogClose() {
      this.nameSelectionDialog.selectedName = "";
      this.nameSelectionDialog.names = [];
      this.nameSelectionDialog.rowData = null;
    },

    selectFactorAndStandard(row) {
      this.fileResourceId = row.id;
      this.fileResourceName = row.fileName;
      this.fileResourceCode = row.fileCode;
      this.choseFatcors = [];
      this.selectedIds = new Set();
      this.factorVisible = true;
      this.factorSelection = [];
      this.groupSelection = [];

      this.getTreeClassList();
      this.getFactorGroup();
      this.handleFactorSearch();

      if (this.$refs.factorTable) {
        this.$refs.factorTable.clearSelection();
      }
      if (this.$refs.groupTable) {
        this.$refs.groupTable.clearSelection();
      }

      // 获取已关联的因子数据并添加到已选列表
      formConfigurationsServer
        .getFactorstandByFileResourceId(row.id)
        .then(res => {
          if (res.code === 200 && res.result) {
            this.choseFatcors = res.result.map(item => {
              return {
                ...item
                // standardCode: item.factorMethodId
              };
            });

            this.choseFatcors.forEach(item => {
              this.selectedIds.add(item.id);
            });

            this.$nextTick(() => {
              if (this.$refs.factorTable) {
                this.$refs.factorTable.clearSelection();
                this.showChoseData.forEach(row => {
                  if (this.selectedIds.has(row.id)) {
                    this.$refs.factorTable.toggleRowSelection(row, true);
                  }
                });
              }

              if (this.$refs.groupTable) {
                this.$refs.groupTable.clearSelection();
                this.showChoseData.forEach(row => {
                  if (this.selectedIds.has(row.id)) {
                    this.$refs.groupTable.toggleRowSelection(row, true);
                  }
                });
              }
            });
          }
        });
    },
    getTreeClassList() {
      dictServer.findTreeClasses().then(res => {
        this.factorTreeData = res.result || [];
      });
    },
    getFactorGroup() {
      factorServer.findHomFactorGroup().then(res => {
        if (res.code === 200) {
          this.factorGroupData = res.result || [];
        }
      });
    },

    handleTreeFactorSearch(val, node) {
      this.factorForm.classId = node.parent.data.id;
      this.factorForm.secdClassId = val.id;
      this.factorForm.factorName = "";
      this.factorForm.pageNumber = 1;
      this.handleFactorSearch();
      // this.$refs.multipleTable.clearSelection();
    },

    handleFactorSearch() {
      factorServer.getFactorListForPage(this.factorForm).then(res => {
        if (res.code === 200) {
          this.showChoseData = res.result.records || [];
          this.factTotal = res.result.total;

          // 如果当前是因子选项卡，则更新显示数据
          // if (this.radio1 === "1") {
          //   this.showChoseData = [...this.factorChoseData];
          //   this.$nextTick(() => {
          //     if (this.$refs.factorTable) {
          //       this.showChoseData.forEach(row => {
          //         if (
          //           this.factorSelected.some(selected => selected.id === row.id)
          //         ) {
          //           this.$refs.factorTable.toggleRowSelection(row, true);
          //         }
          //       });
          //     }
          //   });
          // }
        }
      });
    },
    handleGroupSearch() {
      if (this.groupForm.groupId) {
        factorServer
          .findCheckStandardsByGroupId(this.groupForm.groupId)
          .then(result => {
            if (result.code === 200 && result.result) {
              this.groupChoseData = result.result || [];

              // 如果当前是套餐选项卡，则更新显示数据
              if (this.radio1 === "2") {
                this.showChoseData = [...this.groupChoseData];
                this.$nextTick(() => {
                  if (this.$refs.groupTable) {
                    this.showChoseData.forEach(row => {
                      if (
                        this.groupSelected.some(
                          selected => selected.id === row.id
                        )
                      ) {
                        this.$refs.groupTable.toggleRowSelection(row, true);
                      }
                    });
                  }
                });
              }
            }
          });
      }
    },
    choseItem(val) {
      console.log(val);

      // 保存当前组的选中状态
      if (this.groupForm.groupId && this.groupSelection.length > 0) {
        this.selectedGroupItems.set(this.groupForm.groupId, [
          ...this.groupSelection
        ]);
      }

      this.groupForm.groupId = val.groupId;
      this.name = val.groupName;

      // 切换到新组时，恢复该组之前的选择状态（如果有的话）
      const previousSelection = this.selectedGroupItems.get(val.groupId);
      if (previousSelection) {
        this.$nextTick(() => {
          if (this.$refs.groupTable) {
            this.$refs.groupTable.clearSelection();
            previousSelection.forEach(row => {
              const target = this.showChoseData.find(
                item => item.id === row.id
              );
              if (target) {
                this.$refs.groupTable.toggleRowSelection(target, true);
              }
            });
          }
        });
      } else {
        // 如果没有之前的选择，清除选择
        this.$nextTick(() => {
          if (this.$refs.groupTable) {
            this.$refs.groupTable.clearSelection();
          }
        });
      }

      this.handleGroupSearch();
    },
    handleFactorSelectionChange(val) {
      this.factorSelection = val;

      // 处理因子选择变化
      if (val) {
        val.forEach(i => {
          const ob = this.choseFatcors.find(j => j.id === i.id);
          if (!ob) {
            this.choseFatcors.push({
              ...i,
              isFactor: 0,
              factorMethodId: i.standardCode
            });
          }
        });
      }
    },
    handleGroupSelectionChange(val) {
      console.log(val[0].standardCode);

      this.groupSelection = val;

      // 保存当前组的选中状态
      if (this.groupForm.groupId) {
        if (val && val.length > 0) {
          this.selectedGroupItems.set(this.groupForm.groupId, [...val]);
        } else {
          this.selectedGroupItems.delete(this.groupForm.groupId);
        }
      }

      // 处理套餐选择变化
      if (val && val.length > 0) {
        const mergedItem = {
          id: "merged_" + this.groupForm.groupId, // 使用groupId作为唯一标识
          groupId: this.groupForm.groupId, // 保存groupId用于识别
          factorMethodId: val[0].standardCode,
          isFactor: 1,
          className: val[0].className || "",
          factorName:
            this.name + "(" + val.map(g => g.factorName).join("、") + ")",
          standardNo: val[0].standardNo || "",
          standardName: val[0].standardName || "",
          analysisMethod: val[0].analysisMethod || "",
          subCheckStandardIds: val.map(g => g.standardCode).join(",")
        };

        // 查找是否已存在当前组的合并项
        const existingIndex = this.choseFatcors.findIndex(
          item => item.groupId && item.groupId === this.groupForm.groupId
        );

        if (existingIndex > -1) {
          // 如果已存在当前组的合并项，则替换它
          this.choseFatcors.splice(existingIndex, 1, mergedItem);
        } else {
          // 如果不存在当前组的合并项，则添加新项
          this.choseFatcors.push(mergedItem);
        }
        console.log(mergedItem);
      } else {
        // 移除当前组的合并项
        const existingIndex = this.choseFatcors.findIndex(
          item => item.groupId && item.groupId === this.groupForm.groupId
        );
        if (existingIndex > -1) {
          this.choseFatcors.splice(existingIndex, 1);
        }
      }
    },
    handleSelectionChange(val) {
      if (val) {
        val.forEach(i => {
          const ob = this.choseFatcors.find(j => j.id === i.id);
          if (!ob) {
            this.choseFatcors.push(i);
          }
        });
      }
    },
    handleClose(item) {
      const index = this.choseFatcors.findIndex(i => i.id === item.id);
      if (index > -1) {
        this.choseFatcors.splice(index, 1);
      }

      // 如果是套餐项，还需要清理selectedGroupItems中的记录
      if (item.groupId) {
        this.selectedGroupItems.delete(item.groupId);
        // 如果当前显示的是这个组，清除表格选择
        if (this.groupForm.groupId === item.groupId && this.$refs.groupTable) {
          this.$refs.groupTable.clearSelection();
        }
      }

      // 如果是普通因子项
      if (item.isFactor === 0) {
        // 清除因子表格中的选择状态
        if (this.radio1 === "1" && this.$refs.factorTable) {
          this.$refs.factorTable.toggleRowSelection(item, false);
        }
      }
    },

    getRowKeys(row) {
      return row.id;
    },
    confirmChoseFactor() {

      // if (this.choseFatcors.length === 0) {
      //   this.$message.warning("请至少选择一个因子");
      //   return;
      // }

      // 检查标准号是否一致
      const standardNos = [
        ...new Set(this.choseFatcors.map(item => item.standardNo))
      ];
      if (standardNos.length > 1) {
        this.$message.warning("所选因子的标准号不一致，请重新选择");
        return;
      }

      const divisor = {
        fileResourceId: this.fileResourceId,
        fileResourceName: this.fileResourceName,
        factorstandList: this.choseFatcors,
        fileResourceCode: this.fileResourceCode
      };

      formConfigurationsServer.fileResourceBatchStandard(divisor).then(res => {
        if (res.code == 200) {
          // 清空选中状态
          if (this.$refs.multipleTable) {
            this.$refs.multipleTable.clearSelection();
          }
          this.selectedIds.clear();
          this.choseFatcors = [];

          this.factorVisible = false;
          this.$message({
            type: "success",
            message: res.message
          });
        } else {
          this.$message({
            type: "error",
            message: res.message
          });
        }
      });
    },
    // 查看关联因子和标准
    viewFactorAndStandard(row) {
      var fileResourceId = row.id;
      this.factorDialogVisible = true;
      formConfigurationsServer
        .getFactorstandByFileResourceId(fileResourceId)
        .then(res => {
          if (res.code === 200 && res.result) {
            this.factorData = res.result;
            this.factorDialogVisible = true;
          } else {
            this.$message.error("获取数据失败");
          }
        });
    }
  }
};
</script>

<style scoped>
.card-left {
  width: 100%;
  min-height: 200px;
  max-height: 570px;
}
.card-right {
  width: 100%;
  min-height: 200px;
  max-height: 450px;
}
.el-card {
  overflow: auto;
}
.dialog-item {
  padding-left: 3px;
  line-height: 30px;
  cursor: pointer;
}
.dialog-item:hover {
  background: #e8f4ff;
  border-radius: 3px;
}
.ellipsis {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
